/*
Copyright 2011 Johan Maasing

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nu.zoom.catonine.swing.tail;

import java.util.Iterator;
import java.util.List;

import javax.swing.text.BadLocationException;

import nu.zoom.catonine.prefs.Preferences;
import nu.zoom.catonine.tail.TailerListener.LogEntry;
import nu.zoom.swing.desktop.common.BackendException;
import nu.zoom.swing.desktop.preferences.InvalidDataTypeException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author "Johan Maasing" &lt;johan@zoom.nu&gt;
 * 
 */
public class TruncatingTailingDocument extends TailingDocument {
	private static final long serialVersionUID = -3067233929452085147L;
	private final Log log = LogFactory.getLog(getClass());
	private final Preferences preferences;

	public TruncatingTailingDocument(final Preferences preferences) {
		this.preferences = preferences;
	}

	@Override
	public void lines(List<LogEntry> lines) {
		super.lines(lines);
		truncateDocumentToScrollback();
	}

	private void truncateDocumentToScrollback() {
		try {
			Integer scrollbackSizeSetting = preferences.getScrollbackSize();
			if (scrollbackSizeSetting != null) {
				final int documentLengthBeforeTruncate = getLength();
				int scrollback = scrollbackSizeSetting.intValue() * 1024 * 1024;
				int sizeToReclaim = documentLengthBeforeTruncate - scrollback;
				if (sizeToReclaim > 0) {
					log.debug("Document needs truncation");
					int offsetChange = 0;
					FoldedDocumentLogEntry first = content.peekFirst();
					if ((first == null) || (first.documentOffset != 0)) {
						log.warn("Unable to truncate document, first entry was null or not at offset 0: " + first);
					} else {
						while ((offsetChange < sizeToReclaim) && (content.size() > 0)) {
							FoldedDocumentLogEntry documentLogEntry = content.pop();
							offsetChange += documentLogEntry.documentLength;
							log.debug("Reclaiming entry: " + documentLogEntry);
						}
						if (offsetChange > 0) {
							Iterator<FoldedDocumentLogEntry> iterator = content.iterator();
							while (iterator.hasNext()) {
								DocumentLogEntry documentLogEntry = iterator.next();
								documentLogEntry.documentOffset -= offsetChange;
							}
						}
						try {
							remove(0, offsetChange);
						} catch (BadLocationException e) {
							log.fatal("Unable to remove text from document but content list was updated");
						}
					}
				}
			}
		} catch (InvalidDataTypeException e) {
			log.error(e);
		} catch (BackendException e) {
			log.error(e);
		}

	}

}
